import { useReactive } from "ahooks";
import { useModel } from "umi";
import { useEffect } from "react";
import compress from "gql-compress";

import personFemale from "../../assets/images/person_female.png";
import personMale from "../../assets/images/person_male.png";

const useInstitutionMembers = (oiUuid) => {
    const { graphqlFetch } = useModel("global");
    const { kuboUrl } = useModel("kubo");

    const state = useReactive({
        loading: false,
        members: [],
    });

    const loadInstitutionMembers = async () => {
        if (!oiUuid) return;
        state.loading = true;
        let res = await graphqlFetch({
            query,
            variables: {
                oiUuid,
            },
        });
        let members =
            res?.a?.nodes.map((item, i) => {
                return {
                    id: oiUuid + "-po-" + i,
                    reUuid: item.reUuid,
                    reType: item.reType,
                    oimRemk: item.oimRemk,
                    oiUuid: item.oiUuid,
                    ...item.member,
                    value: {
                        name: item.member.omPosi,
                        title: item.member.omName,
                        type: "机构成员",
                        icon: item.member?.omAvta ? kuboUrl + item.member.omAvta : item.member.omRoge === "男" ? personMale : personFemale,
                    },
                };
            }) || [];
        state.members = members;
        state.loading = false;
        return members;
    };

    useEffect(() => {
        oiUuid && loadInstitutionMembers();
    }, [oiUuid]);

    return { ...state, loadInstitutionMembers };
};

const query = compress(`query MyQuery($oiUuid: UUID!) {
    a:allOrganizationInstitutionsMembers(condition: { oiUuid: $oiUuid }) {
        nodes {
            reUuid
            reType
            oimRemk
            oiUuid
            member: organizationMemberByOmUuid {
                omUuid
                omName
                omAvta
                omRoge
                omPosi
                omEona
                omEouu
            }
        }
    }
}`);

export default useInstitutionMembers;
